library(stringr)

setwd("C:/UQAR/Recherche/Maitrise/Donnees/Bylot/Brutes/GPS")

gpsbabel <- '"C:/Program Files/GPSBabel/gpsbabel.exe"'
options <- '-t -i gdb,via=0,roadbook=0
            -f __FILE_SRC__
            -x track,pack -o "garmin_txt,date=dd/mm/yyyy,datum=NAD 83,dist=m,grid=utm,prec=6"
            -F __FILE_DEST__'
destPath <- "test"
ext <- ".txt"

files <- list.files(pattern="*.gdb")

for (i in files) {
  print(i)
  opts <- str_replace(options,  "__FILE_SRC__", file.path(getwd(), i))
  filename <- file.path(getwd(), destPath, unlist(strsplit(i, "\\."))[1])
  opts <- str_replace(opts, "__FILE_DEST__", paste(filename, ext, sep=""))
  opts <- str_replace_all(opts, "\n", "")
  system(paste(gpsbabel,opts), intern=T)
}

files <- list.files(path="./txt", pattern="GPS._.?_.*.txt")

for (i in files) {
  f <- file(paste(destPath, i, sep="/"), open="r")
  tmp <-readLines(f)
  tmp <- tmp[-c(1:9, 11)]
  close(f)
  f <- file(paste(destPath, i, sep="/"), open="w+")
  writeLines(tmp, f)
  close(f)
  tmp <- NULL
}

